package creator;

import java.io.FileWriter;
import java.io.IOException;

public class ServiceCreator {
	public static void createFile(String dir, ObjectInfo o) {
		createServiceJavaFile(dir, o);
		createServiceImplJavaFile(dir, o);
	}
	
	public static void createServiceJavaFile(String dir, ObjectInfo o) {
		String iserviceName = o.iserviceName();
		String fileName = String.format("%s/service/%s.java", dir, iserviceName);
		
		try {
			FileCreator.createFile(fileName);
			FileWriter fw = new FileWriter(fileName);
			String packageName = o.getPackageName();
			
			fw.write(String.format("package %s.service;\n\n", packageName));
			
			fw.write(String.format("import %s;\n\n", o.fullName()));
			
			fw.write(String.format("public interface %s {\n\n", iserviceName));
			
			fw.write("}\n");
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void createServiceImplJavaFile(String dir, ObjectInfo o) {
		String serviceName = o.serviceName();
		String fileName = String.format("%s/service/impl/%s.java", dir, serviceName);
		
		try {
			FileCreator.createFile(fileName);
			FileWriter fw = new FileWriter(fileName);
			String packageName = o.getPackageName();
			
			fw.write(String.format("package %s.service.impl;\n\n", packageName));
			
			fw.write(String.format("import %s;\n", o.fullName()));
			fw.write(String.format("import %s;\n\n", o.idaoFullName()));
			
			fw.write(String.format("public class %s implements %s {\n\n", serviceName, o.iserviceName()));
			fw.write(String.format("    private %s %s;\n\n", o.idaoName(), formatVarName(o.daoName())));
			createGetter(fw, o);
			createSetter(fw, o);
			fw.write("}\n");
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 针对对象的变量名格式化
	 * @param typeName 对象类型名
	 * @return
	 */
	public static String formatVarName(String daoTypeName) {
		String firstLetter = daoTypeName.substring(0, 1);
		firstLetter = firstLetter.toLowerCase();
		
		return firstLetter + daoTypeName.substring(1);
	}
	
	public static void createGetter(FileWriter fw, ObjectInfo o) throws IOException {
		String daoName = o.daoName();
		String var = formatVarName(daoName);
		fw.write(String.format("    public %s get%s() {\n", o.idaoName(), daoName));
		fw.write(String.format("        return %s;\n", var));
		fw.write("    }\n\n");
	}
	
	public static void createSetter(FileWriter fw, ObjectInfo o) throws IOException {
		String daoName = o.daoName();
		String var = formatVarName(daoName);
		fw.write(String.format("    public void set%s(%s %s) {\n", daoName, o.idaoName(), var));
		fw.write(String.format("        this.%s = %s;\n", var, var));
		fw.write("    }\n\n");
	}
}
